import { createRouterInstanceDefault, importRoutes, AppRouteRecordRaw } from '@fssc/admin';
import { RouteRecordRaw } from 'vue-router';
import { useAppStoreWithOut, usePermissionStoreWithOut, useUserStoreWithOut } from '../store';

/**
 * 不重定向白名单
 */
export const NO_REDIRECT_WHITE_LIST = ['/login'];

/**
 * 需要权限的路由配置
 */
const routes = importRoutes(import.meta.glob(
  ['@/views/**/route.ts'],
  {
    eager: true,
  },
));

/**
 * 路由实例
 */
const router = createRouterInstanceDefault(import.meta.env.VITE_ROUTER_HISTORY, [], []);

router.beforeEach(async (to, from, next) => {
  const permissionStore = usePermissionStoreWithOut();
  const userStore = useUserStoreWithOut();
  if (userStore.getUserInfo) {
    if (to.path === 'login') {
      next({ path: '/' });
    } else {
      if (permissionStore.getIsAddRouters) {
        next();
        return;
      }
      permissionStore.generateRoutes(routes, userStore.getUserInfo?.menuCodeList);
      permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw);
      });
      permissionStore.setIsAddRouters(true);
      const redirectPath = from.query.redirect || to.path;
      const redirect = decodeURIComponent(redirectPath as string);
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
      permissionStore.setIsAddRouters(true);
      next(nextData);
    }
  } else if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
    next();
  } else {
    next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
  }
});

router.afterEach(async (to, from) => {
});

export default router;
